package com.epoch.client.view;

import com.epoch.client.kernel.constant.CommonStorage;
import com.epoch.client.kernel.listener.EnterListener;
import com.epoch.client.kernel.serve.SocketMappingManager;
import com.epoch.common.Message;
import com.epoch.common.MessageType;
import com.epoch.common.User;
import lombok.extern.slf4j.Slf4j;

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.Socket;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 *聊天的界面类，注意客户端要时时刻刻的读取服务器的信息
 *因为要处于读取状态，所以要变为线程
 *在线用户提示还未实现
 */

@Slf4j
public class ChatFrame extends JFrame implements Runnable {

    String username;
    Integer userId;
    Integer GroupID;

    JTextField textServerIP;// IP
    JTextField textServerPort;// 端口
    public JTextArea textAreaRecord;// 消息文本记录框
    public JTextArea textAreaMsg;// 消息框
    JButton btnSend;// 发送按钮
    JButton btnQuit;// 退出按钮
    JButton btnInit;// 初始化聊天记录按钮
    JLabel jlUsername;// 用户名

    public ChatFrame(Integer groupId,String username) {
        this.username = username;
        this.GroupID = groupId;

        this.getContentPane().setBackground(new Color(180,220,230));
        Font font = new Font("华文行楷", 0, 15);
        Color color = new Color(193,210,240);

        // IP
        JLabel lblNewLabel = new JLabel("群 ID:");
        lblNewLabel.setFont(font);
        lblNewLabel.setBounds(14, 24, 121, 18);
        this.getContentPane().add(lblNewLabel);
        textServerIP = new JTextField();
        textServerIP.setBackground(color);
        textServerIP.setText(groupId.toString());
        textServerIP.setEditable(false);
        textServerIP.setBounds(121, 21, 121, 24);
        this.getContentPane().add(textServerIP);
        textServerIP.setColumns(10);

        // 端口
        JLabel lblNewLabel_1 = new JLabel("端口号:");
        lblNewLabel_1.setFont(font);
        lblNewLabel_1.setBounds(256, 24, 58, 18);
        this.getContentPane().add(lblNewLabel_1);
        textServerPort = new JTextField();
        textServerPort.setEditable(false);
        textServerPort.setText("8000");
        textServerPort.setBackground(color);
        textServerPort.setBounds(313, 21, 48, 24);
        this.getContentPane().add(textServerPort);
        textServerPort.setColumns(10);

        // 用户名
        JLabel label_1 = new JLabel("用户名:");
        label_1.setFont(font);
        label_1.setBounds(375, 24, 58, 18);
        this.getContentPane().add(label_1);
        jlUsername = new JLabel(username);
        jlUsername.setBounds(433, 21, 95, 24);
        this.getContentPane().add(jlUsername);

        //退出按钮
        btnQuit = new JButton("退出");
        btnQuit.setFont(font);
        btnQuit.setBounds(596, 20, 95, 27);
        this.getContentPane().add(btnQuit);
        btnQuit.setBackground(new Color(150,200,230));
        btnQuit.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent arg0) {
                if(arg0.getSource() == btnQuit)
                    dispose();
                new ChooseGroup(username);
            }
        });

        btnInit = new JButton("加载聊天记录");
        btnInit.setFont(font);
        btnInit.setBounds(250, 409, 150, 27);
        this.getContentPane().add(btnInit);
        btnInit.setBackground(new Color(150,200,230));
        btnInit.addActionListener((actionEvent) -> {
            Message message = new Message();
            message.setMessageType(MessageType.MESSAGE_INITHIS);
            message.setGroupId(groupId);
            try {
                ObjectOutputStream oos =
                        new ObjectOutputStream(SocketMappingManager.getSocket(username).getOutputStream());
                oos.writeObject(message);
            } catch (IOException ioException) {
                ioException.printStackTrace();
            }
        });

        // 发送按钮
        btnSend = new JButton("发送");
        btnSend.setFont(font);
        btnSend.setBounds(444, 409, 88, 27);
        this.getContentPane().add(btnSend);
        btnSend.setBackground(new Color(150,200,230));
        // 连接按钮事件处理程序
        btnSend.addActionListener(new EnterListener(textAreaRecord, textAreaMsg, this, groupId));

        // 聊天记录框
        JLabel label = new JLabel("聊天区");
        label.setFont(font);
        label.setBounds(14, 55, 72, 18);
        this.getContentPane().add(label);
        JScrollPane scrollPane = new JScrollPane();
        scrollPane.setBounds(14, 72, 518, 228);
        this.getContentPane().add(scrollPane);
        textAreaRecord = new JTextArea();
        textAreaRecord.setBackground(Color.WHITE);
        textAreaRecord.setEditable(false);
        scrollPane.setViewportView(textAreaRecord);

        // 消息输入框
        JScrollPane scrollPane_1 = new JScrollPane();
        scrollPane_1.setBounds(14, 332, 518, 73);
        this.getContentPane().add(scrollPane_1);
        textAreaMsg = new JTextArea();
        scrollPane_1.setViewportView(textAreaMsg);

        JLabel label_2 = new JLabel("在线用户");
        label_2.setFont(font);
        label_2.setBounds(543, 55, 72, 18);
        this.getContentPane().add(label_2);

        // 用户列表框
        JScrollPane scrollPane_2 = new JScrollPane();
        scrollPane_2.setBounds(546, 72, 149, 334);
        this.getContentPane().add(scrollPane_2);
        /**
         * 暂未实现。。。
         */

        this.setResizable(false);
        this.setTitle("群聊主界面");
        this.setIconImage((new ImageIcon(this.getClass().getResource("/imgs/login_title.png"))).getImage());
        this.setBounds(410, 194, 715, 476);
        this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        this.getContentPane().setLayout(null);
        this.setVisible(true);

        Dimension scr = Toolkit.getDefaultToolkit().getScreenSize();
        Dimension fra = this.getSize();
        int width = (int) (scr.getWidth()-fra.getWidth())/2;
        int height = (int) (scr.getHeight() - fra.getHeight())/2;
        this.setLocation(width,height);

    }

    @Override
    public void run() {
        Socket s = SocketMappingManager.getSocket(username);
        /*
        通过ContextHolder获得到的用户对象
        */
        Thread thread = Thread.currentThread();
        log.info("ChatFrame的线程id为" + thread.getId());
        User user = (User) CommonStorage.REPOSITORY.get("user");
        log.info("仓库中的对象user = " + user);
        while(true) {
            try {
                ObjectInputStream ois = new ObjectInputStream(s.getInputStream());
                Message message = (Message) ois.readObject();
                if (message.getDynamicData() != null) {
                    // 把获取到的对象转为List
                    Object obj = message.getDynamicData().get("recordList");
                    List<String> records = new ArrayList<>();
                    if (obj instanceof ArrayList<?>) {
                        for (Object o : (List<?>) obj) {
                            records.add((String) o);
                        }
                    }
                    for (String record : records) {
                        textAreaRecord.append(record + "\n");
                    }
                } else {
                    String info = message.getDate()+ " " + message.getSenderName() + "说：" + message.getMessage() + "\n";
                    textAreaRecord.append(info);
                }
            } catch (Exception e) {
                JOptionPane.showMessageDialog(null,"连接已中断！");
                e.printStackTrace();
                System.exit(1);
            }
        }
    }
}













//界面居中代码
//Dimension scr = Toolkit.getDefaultToolkit().getScreenSize();
//Dimension fra = this.getSize();
//int width = (scr.width - fra.width)/2;
//int height = (scr.height - fra.height)/2;